package com.youdianda.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectPage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youdianda.context.BaseContext;
import com.youdianda.controller.ydd.UserController;
import com.youdianda.dto.PageQueryDTO;
import com.youdianda.dto.YddLinkPageDTO;
import com.youdianda.dto.YddUserFavoriteLikesArticleDTO;
import com.youdianda.entity.YddArticle;
import com.youdianda.entity.YddUser;
import com.youdianda.entity.YddUserData;
import com.youdianda.mapper.YddUserDataMapper;
import com.youdianda.mapper.YddUserMapper;
import com.youdianda.result.PageResult;
import com.youdianda.result.Result;
import com.youdianda.service.YddArticleService;
import com.youdianda.constant.MessageConstant;
import com.youdianda.dto.PageQueryDTO;
import com.youdianda.dto.YddArticlePageDTO;
import com.youdianda.entity.*;
import com.youdianda.result.PageResult;
import com.youdianda.result.Result;
import com.youdianda.service.*;
import com.youdianda.mapper.YddArticleMapper;
import com.youdianda.service.YddUserService;
import com.youdianda.vo.YddUserFavoriteLikesArticle;
import org.apache.ibatis.reflection.wrapper.BaseWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.youdianda.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xliu
 * @description 针对表【ydd_article】的数据库操作Service实现
 * @createDate 2023-05-14 16:01:34
 */
@Service
public class YddArticleServiceImpl extends ServiceImpl<YddArticleMapper, YddArticle> implements YddArticleService {

    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private YddUserDataService yddUserDataService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private YddTagService yddTagService;

    @Autowired
    private YddLinkService yddLinkService;
    @Autowired
    private YddAdvimgService yddAdvimgService;
    @Autowired
    private YddAdvposService yddAdvposService;

    @Autowired
    private YddArticleMapper yddArticleMapper;

    @Autowired
    private YddUserDataMapper yddUserDataMapper;

    @Autowired
    private YddUserMapper yddUserMapper;

    /**
     * 我的文章
     *
     * @param dto
     * @return
     */
    @Override
    public Result<PageResult> myArticle(PageQueryDTO dto) {
        //获取登录人信息
        Long currentId =BaseContext.getCurrentId();
        //根据登录人id查询文章信息
        LambdaQueryWrapper<YddArticle> lqw = Wrappers.lambdaQuery();
        lqw.eq(YddArticle::getUser_id, currentId);
        //开启分页
        IPage<YddArticle> ipage = new Page<>(Long.valueOf(dto.getPage()), Long.valueOf(dto.getLimit()));
        yddArticleMapper.selectPage(ipage, lqw);
        //封装返回
        PageResult result = new PageResult();
        result.setCount((int) ipage.getTotal());
        result.setCurrentPage((int) ipage.getCurrent());
        result.setPageSize((int) ipage.getSize());
        result.setTotalPages((int) ipage.getPages());
        result.setData(ipage.getRecords());
        return Result.success(result);
    }

    /**
     * 我的收藏/点赞文章
     *
     * @param dto
     * @return
     */
    @Override
    public Result userDataList(YddLinkPageDTO dto) {
        //获取登录人信息
        Long currentId = BaseContext.getCurrentId();

        LambdaQueryWrapper<YddUserData> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(YddUserData::getUser_id, currentId).eq(YddUserData::getType, dto.getType());

        List<YddUserData> yddUserDataList = yddUserDataMapper.selectList(queryWrapper);
        List<Integer> list = yddUserDataList.stream().map(yddUserData -> yddUserData.getArticle_id()).collect(Collectors.toList());

        if (list == null || list.size() == 0) {
            return Result.success();
        }

        LambdaQueryWrapper<YddArticle> lqw = Wrappers.lambdaQuery();
        lqw.in(YddArticle::getId, list);
        //开启分页
        IPage<YddArticle> ipage = new Page<>(Long.valueOf(dto.getPage()), Long.valueOf(dto.getLimit()));
        page(ipage, lqw);

        //封装返回
        PageResult result = new PageResult();
        result.setCount((int) ipage.getTotal());
        result.setCurrentPage((int) ipage.getCurrent());
        result.setPageSize((int) ipage.getSize());
        result.setTotalPages((int) ipage.getPages());
        result.setData(ipage.getRecords());


        YddUserFavoriteLikesArticle yddUserFavoriteLikesArticle = new YddUserFavoriteLikesArticle();
        yddUserFavoriteLikesArticle.setList(result);
        return Result.success(yddUserFavoriteLikesArticle);
    }

    /**
     * 修改文章
     *
     * @param yddArticle
     * @return
     */
    @Override
    public Result editArticle(YddArticle yddArticle) {
        if (yddArticle.getId() == null) {
            return Result.error("id为空");
        }

        update(Wrappers.<YddArticle>lambdaUpdate()
                .set(StringUtils.hasLength(yddArticle.getTitle()), YddArticle::getTitle, yddArticle.getTitle())
                .set(StringUtils.hasLength(yddArticle.getAuthor()), YddArticle::getAuthor, yddArticle.getAuthor())
                .eq(YddArticle::getId, yddArticle.getId()));
        updateById(yddArticle);
        return Result.success();
    }

    /**
     * 修改用户资料
     *
     * @param yddUser
     * @return
     */
    @Override
    public Result updateUserInfo(YddUser yddUser) {
        if (yddUser.getId() == null) {
            return Result.error("id为空");
        }

        //修改信息
        yddUserMapper.updateById(yddUser);
        return Result.success();
    }

    /**
     * 点赞/取消点赞和收藏/取消收藏
     *
     * @param dto
     * @return
     */
    @Override
    public Result userDataHandle(YddUserFavoriteLikesArticleDTO dto) {

        Long currentId = BaseContext.getCurrentId();

        YddUserData yddUserData = new YddUserData();
        BeanUtils.copyProperties(dto, yddUserData);
        yddUserData.setUser_id(Math.toIntExact(currentId));

        if (dto.getAction().equals("add")) {
            yddUserDataMapper.insert(yddUserData);
        }
        if (dto.getAction().equals("del")) {
            LambdaQueryWrapper<YddUserData> lqw = Wrappers.lambdaQuery();
            lqw.eq(YddUserData::getArticle_id, dto.getArticle_id())
                    .eq(YddUserData::getUser_id,currentId)
                    .eq(YddUserData::getType, dto.getType());
            yddUserDataMapper.delete(lqw);
        }
        return Result.success();

    }


    /**
     * 分页查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public Result page(YddArticlePageDTO dto) {
        if (dto.getPage() == null) {
            dto.setPage("1");
        }
        if (dto.getLimit() == null) {
            dto.setLimit("10");
        }
        //使用mybedispuls分页功能
        Page<YddArticle> articlePage = new Page<>(Integer.valueOf(dto.getPage()),Integer.valueOf(dto.getLimit()));
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        //文章标题，支持模糊查询
        if (dto.getTitle() != null&&dto.getTitle() != "") {
            queryWrapper.like(YddArticle::getTitle,dto.getTitle());
        }
//        if (dto.getType() != null&&dto.getType() != "") {
//            queryWrapper.eq(YddArticle::getTags,dto.getType());
//        }
        if (dto.getStart_time() != null&&dto.getStart_time() != "") {
            queryWrapper.ge(YddArticle::getCreate_date,dto.getStart_time());
        }
        if (dto.getEnd_time() != null&&dto.getEnd_time() != "") {
            queryWrapper.le(YddArticle::getCreate_date,dto.getEnd_time());
        }
        if (dto.getCateid() != null&&dto.getEnd_time() != "") {
            queryWrapper.eq(YddArticle::getCateid,dto.getCateid());
        }
        IPage<YddArticle> page = page(articlePage, queryWrapper);
//        Page<YddArticle> page = yddArticleMapper.selectPage(articlePage, queryWrapper);

        Integer total = Math.toIntExact(page.getTotal());
        List<YddArticle> records = page.getRecords();
        ArrayList<YddArticleVO> yddArticleVOS = new ArrayList<>(records.size());
        for (YddArticle yddArticle : records) {
            YddCate cate = yddCateService.getById(yddArticle.getCateid());
            YddArticleVO vo = new YddArticleVO();
            BeanUtils.copyProperties(yddArticle,vo);
            vo.setCatename(cate.getCatename());
            yddArticleVOS.add(vo);
        }
        Integer pages = Math.toIntExact(page.getPages());
        Integer current = Math.toIntExact(page.getCurrent());
        Integer pageSize = Math.toIntExact(page.getSize());

        PageResult pageResult = new PageResult(total,pages,pageSize,current,yddArticleVOS);

        return Result.success(pageResult);
    }

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result del(String id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        removeById(id);

        return Result.success();
    }


    /**
     * 文章详情
     *
     * @param id
     * @return
     */
    @Override
    public Result rowInfo(String id) {
        YddArticle yddArticle = getById(id);

        return Result.success(yddArticle);
    }

    /**
     * 请求参数
     *
     * @param yddArticle
     * @return
     */
    @Override
    @Transactional
    public Result update(YddArticle yddArticle) {
        yddArticle.setUpdate_date(System.currentTimeMillis());
        updateById(yddArticle);

        return Result.success();
    }

    /**
     * 热门置顶文章数据(首页)
     *
     * @param dto
     * @return
     */
    @Override
    public Result indexNew(PageQueryDTO dto) {
        Page<YddArticle> articlepage = new Page<>(Integer.valueOf(dto.getPage()), Integer.valueOf(dto.getLimit()));

        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(YddArticle::getIshot,"1").eq(YddArticle::getIstop,"1");
//        queryWrapper.eq(YddArticle::getIstop,"1");

        Page<YddArticle> page = page(articlepage, queryWrapper);
        Integer total = Math.toIntExact(page.getTotal());
        List<YddArticle> records = page.getRecords();
        Integer pages = Math.toIntExact(page.getPages());
        Integer current = Math.toIntExact(page.getCurrent());
        Integer pageSize = Math.toIntExact(page.getSize());

        PageResult pageResult = new PageResult(total, pages, pageSize, current, records);


        long timeMillis = System.currentTimeMillis();
        //获取24小时的文章数
        queryWrapper.ge(YddArticle::getCreate_date,timeMillis-(24*3600*1000));
        long num_day = count(queryWrapper);

        //一周数据
        long begin = timeMillis - (7 * 24 * 60 * 60 * 1000);
        queryWrapper.between(YddArticle::getCreate_date, begin, timeMillis);
        long num_week = count(queryWrapper);

        ArticleDataVO vo = new ArticleDataVO();

        vo.setNum_day(String.valueOf(num_day));
        vo.setNum_week(String.valueOf(num_week));
        vo.setList(pageResult);

        return Result.success(vo);
    }

    /**
     * 文章列表数据
     *
     * @param dto
     * @return
     */
    @Override
    public Result list(YddArticlePageDTO dto) {
        //使用mybedispuls分页功能
        Page<YddArticle> articlePage = new Page<>(Integer.valueOf(dto.getPage()),Integer.valueOf(dto.getLimit()));

        QueryWrapper<YddArticle> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("cateid",dto.getCateid());

        IPage<YddArticle> page = page(articlePage, queryWrapper);

        Integer total = Math.toIntExact(page.getTotal());
        List<YddArticle> records = page.getRecords();
        Integer pages = Math.toIntExact(page.getPages());
        Integer current = Math.toIntExact(page.getCurrent());
        Integer pageSize = Math.toIntExact(page.getSize());

        PageResult pageResult = PageResult.builder()
                .count(total)
                .currentPage(current)
                .pageSize(pageSize)
                .data(records)
                .totalPages(pages)
                .build();

        Map map =new HashMap();
        map.put("list",pageResult);
        return Result.success(map);

    }

    /**
     * 注册
     *
     * @param yddUser
     * @return
     */
    @Override
    public Result reg(YddUser yddUser) {
        //存在就修改，否则新增
        yddUserService.saveOrUpdate(yddUser);
        return Result.success();
    }

    /**
     * 最新文章
     *
     * @return
     */
    @Override
    public Result hot() {
        Page<YddArticle> page = new Page<>(1, 10);
        QueryWrapper<YddArticle> queryWrapper = new QueryWrapper();
        queryWrapper.select("cateid","id","title","pic","click");
        queryWrapper.orderByDesc("create_date");
        IPage<YddArticle> articlePage = page(page, queryWrapper);
        List<YddArticle> articleList = articlePage.getRecords();
       /* QueryWrapper<YddArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("cateid","id","title","pic","click");
        queryWrapper.orderByDesc("create_date");
        List<YddArticle> articleList = list(queryWrapper);*/
        YddUserFavoriteLikesArticle yddUserFavoriteLikesArticle = new YddUserFavoriteLikesArticle(articleList);

        return Result.success(yddUserFavoriteLikesArticle);
    }

    /**
     * 推荐文章
     *
     * @return
     */
    @Override
    public Result recommend() {
        Page<YddArticle> page = new Page<>(1, 10);
        QueryWrapper<YddArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("cateid","id","title","pic","click");
        queryWrapper.eq("ishot","1");
        queryWrapper.orderByDesc("create_date");

        Page<YddArticle> articlePage = page(page, queryWrapper);
        YddUserFavoriteLikesArticle yddUserFavoriteLikesArticle = new YddUserFavoriteLikesArticle(articlePage);
        return Result.success(yddUserFavoriteLikesArticle);
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @Override
    public Result index() {


        //查询分类
        List<YddCate> allCate = yddCateService.list();

        //查询config 要list和data
        List<SysConfig> configlist = sysConfigService.list();
        //list
        List<SysConfig> baseList = configlist.stream().filter(sysConfig -> sysConfig.getTab_value() == "base").collect(Collectors.toList());
        List<SysConfig> baseList1 = configlist.stream().filter(sysConfig -> sysConfig.getGroup_value() == "站点配置").collect(Collectors.toList());
        ArrayList<SysConfigVO> sysConfigVOS1 = new ArrayList<>();
        BeanUtils.copyProperties(baseList1,sysConfigVOS1);
        SysConfigChildren baseChildren1 = new SysConfigChildren("站点配置",sysConfigVOS1);

        List<SysConfig> baseList2 = configlist.stream().filter(sysConfig -> sysConfig.getGroup_value() == "底部信息").collect(Collectors.toList());
        ArrayList<SysConfigVO> sysConfigVOS2 = new ArrayList<>();
        BeanUtils.copyProperties(baseList2,sysConfigVOS2);
        SysConfigChildren baseChildren2 = new SysConfigChildren("底部信息",sysConfigVOS2);

        List<SysConfig> baseList3 = configlist.stream().filter(sysConfig -> sysConfig.getGroup_value() == "其他配置").collect(Collectors.toList());
        ArrayList<SysConfigVO> sysConfigVOS3 = new ArrayList<>();
        BeanUtils.copyProperties(baseList3,sysConfigVOS3);
        SysConfigChildren baseChildren3 = new SysConfigChildren("其他配置",sysConfigVOS3);

        List<SysConfigChildren> children1 = new ArrayList<>();
        children1.add(baseChildren1);
        children1.add(baseChildren2);
        children1.add(baseChildren3);
        SysConfigData sysConfigData1 = new SysConfigData("基础配置","base",children1);

        List<SysConfig> systemList = configlist.stream().filter(sysConfig -> sysConfig.getTab_value() == "custom").collect(Collectors.toList());
        List<SysConfig> systemList1 = configlist.stream().filter(sysConfig -> sysConfig.getGroup_value() == "管理系统配置").collect(Collectors.toList());
        ArrayList<SysConfigVO> sysConfigVOS4 = new ArrayList<>();
        BeanUtils.copyProperties(systemList1,sysConfigVOS4);
        SysConfigChildren systemChildren = new SysConfigChildren("管理系统配置",sysConfigVOS4);

        List<SysConfigChildren> children2 = new ArrayList<>();
        children2.add(systemChildren);
        SysConfigData sysConfigData2 = new SysConfigData("系统配置","system",children2);

        List<SysConfig> customList = configlist.stream().filter(sysConfig -> sysConfig.getTab_value() == "system").collect(Collectors.toList());
        List<SysConfig> customList1 = configlist.stream().filter(sysConfig -> sysConfig.getGroup_value() == "通知公告").collect(Collectors.toList());
        ArrayList<SysConfigVO> sysConfigVOS5 = new ArrayList<>();
        BeanUtils.copyProperties(customList1,sysConfigVOS5);
        SysConfigChildren customChildren1 = new SysConfigChildren("通知公告",sysConfigVOS5);

        List<SysConfig> customList2 = configlist.stream().filter(sysConfig -> sysConfig.getGroup_value() == "前台图片").collect(Collectors.toList());
        ArrayList<SysConfigVO> sysConfigVOS6 = new ArrayList<>();
        BeanUtils.copyProperties(customList2,sysConfigVOS6);
        SysConfigChildren customChildren2 = new SysConfigChildren("前台图片",sysConfigVOS6);

        List<SysConfigChildren> children3 = new ArrayList<>();
        children2.add(customChildren1);
        children2.add(customChildren2);
        SysConfigData sysConfigData3 = new SysConfigData("其他配置","custom",children3);

        List<SysConfigData> list = new ArrayList<>();
        list.add(sysConfigData1);
        list.add(sysConfigData2);
        list.add(sysConfigData3);


        QueryWrapper<SysConfig> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.select("id","attr_key","tab_value","validator","config_value","type");
        List<SysConfig> data = sysConfigService.list(queryWrapper1);
        List<SysConfigVO> allData = new ArrayList<>();
        BeanUtils.copyProperties(data,allData);


        //配置
        SysConfigAllVO sysConfigAllVO = new SysConfigAllVO();
        sysConfigAllVO.setAllData(allData);
        sysConfigAllVO.setList(list);






        //查询allTag所有标签
        QueryWrapper<YddTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","tagname");
        List<YddTag> tagList = yddTagService.list(queryWrapper);
        //查询allLink所有友情链接（文字和图片）
        List<YddLink> linkList = yddLinkService.list();

        //查询banner轮播图数据
        QueryWrapper<YddAdvpos> qw1 = new QueryWrapper<>();
        qw1.eq("advposname","首页Banner");
        YddAdvpos yddAdvpos = yddAdvposService.getOne(qw1);

        LambdaQueryWrapper<YddAdvimg> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(YddAdvimg::getAdvimgpos,yddAdvpos.getId());
        List<YddAdvimg> advimgList =yddAdvimgService.list(qw2);

        //查询sideBanner侧边栏图片
        QueryWrapper<YddAdvpos> qw3 = new QueryWrapper<>();
        qw3.eq("advposname","首页小广告位");
        YddAdvpos yddAdvpos1 = yddAdvposService.getOne(qw3);

        LambdaQueryWrapper<YddAdvimg> qw4 = new LambdaQueryWrapper<>();
        qw4.eq(YddAdvimg::getAdvimgpos,yddAdvpos.getId());
        List<YddAdvimg> advimgList1 =yddAdvimgService.list(qw4);

        //查询showBanner详情广告图
        QueryWrapper<YddAdvpos> qw5 = new QueryWrapper<>();
        qw5.eq("advposname","详情页广告位1");
        YddAdvpos yddAdvpos2 = yddAdvposService.getOne(qw5);

        LambdaQueryWrapper<YddAdvimg> qw6 = new LambdaQueryWrapper<>();
        qw6.eq(YddAdvimg::getAdvimgpos,yddAdvpos.getId());
        List<YddAdvimg> advimgList2 =yddAdvimgService.list(qw6);

        HomeAndGlobalDataVO vo = HomeAndGlobalDataVO.builder()
                .allCate(allCate)
                .config(sysConfigAllVO)
                .allTag(tagList)
                .allLink(linkList)
                .banner(advimgList)
                .showBanner(advimgList2)
                .sideBanner(advimgList1)
                .build();
        return Result.success(vo);
    }

    /**
     * 文章详情数据
     *
     * @param id
     * @return
     */
    @Override
    public Result show(String id) {
        // 上一篇数据
        QueryWrapper<YddArticle> qw1 = new QueryWrapper<>();
        Integer newId = Integer.valueOf(id);

        qw1.eq("id",newId-1);
        qw1.select("id","title");
        List<YddArticle> prev = list(qw1);
        // 下一篇数据
        QueryWrapper<YddArticle> qw2 = new QueryWrapper<>();
        Integer newId2 = Integer.valueOf(id);

        qw1.eq("id",newId2+1);
        qw1.select("id","title");
        List<YddArticle> next = list(qw2);
        // 文章详情数据

        YddArticle info = getById(id);
        Integer cateid = info.getCateid();
        YddCate yddCate = yddCateService.getById(cateid);
        String catename=yddCate.getCatename();

        LambdaQueryWrapper<YddUserData> qw4 = new LambdaQueryWrapper<>();
        qw4.eq(YddUserData::getArticle_id,id);
        List<YddUserData> yddUserData =yddUserDataService.list(qw4);
        Boolean isLike = false;
        Boolean isCollect = false;
        for (YddUserData userData : yddUserData) {
            if (userData.getType() == 1) {
                isLike = true;
                isCollect = false;
            }else {
                isLike = true;
                isCollect = true;
            }
        }

        YddArticleVO newInfo = new YddArticleVO();
        BeanUtils.copyProperties(info,newInfo);
        newInfo.setCatename(catename);
        newInfo.setIsLike(isLike);
        newInfo.setIsCollect(isCollect);

        // 推荐文章数据
        LambdaQueryWrapper<YddArticle> qw3 = new LambdaQueryWrapper<>();
        qw3.eq(YddArticle::getIshot,"1");
        List<YddArticle> recommend = list(qw3);

        ArticleDetailsVO vo = ArticleDetailsVO.builder()
                .info(newInfo)
                .next(next)
                .prev(prev)
                .recommend(recommend)
                .build();
        return Result.success(vo);



    }

    /**
     * 发布文章
     *
     * @param yddArticle
     * @return
     */
    @Override
    public Result addArticle(YddArticle yddArticle) {

        Long currentId = BaseContext.getCurrentId();

        if (yddArticle.getUser_id() == null) {
            return Result.error("用户id为空");
        }

        yddArticle.setUser_id(Math.toIntExact(currentId));
        yddArticle.setCreate_date(System.currentTimeMillis());
        yddArticle.setUpdate_date(System.currentTimeMillis());

        yddArticleMapper.addArticle(yddArticle);
        return Result.success();
    }
}



